//
//  TSCreateTaskTableView.m
//  chart
//
//  Created by 曾斌 on 16/3/27.
//  Copyright (c) 2016年 xu. All rights reserved.
//
#import "TSCreateTaskTableView.h"
#import "TSMsgContentItemCell.h"
#import "TSMsgDatePickerTextFieldCell.h"
#import "TSPickerViewTextFieldCell.h"
#import "FBFilesTableViewController.h"
@implementation TSCreateTaskTableView{
    NSArray *rowsArray;
    BOOL isManualScroll;
    CGPoint point;
    NSMutableDictionary * cellDic;
}

@synthesize msgModel,idsDic;

- (id)initWithFrame:(CGRect)frame
{
    idsDic = [[NSMutableDictionary alloc] initWithCapacity:10];
    if (self=[super initWithFrame:frame]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMultipleSelectCompelete:) name:TSNotification_OnMultipleSelectCompelete object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveContentViewController:) name:TSNotification_SaveContentController object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShown:) name:UIKeyboardDidShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHidden:) name:UIKeyboardDidHideNotification object:nil];
        
        
        rowsArray = @[@"标题:", @"内容:",@"开始时间:",@"结束时间:", @"主办人:", @"监督人:", @"审核人:",@"类型:",@"附件:"];
        
        self.dataSource = self;
        self.delegate = self;
        self.scrollEnabled=YES;
        self.tableFooterView = [[UIView alloc] init];
        cellDic  = [[NSMutableDictionary alloc] initWithCapacity:10];
    }
    
    return self;
}

-(void) initDic{
    if(msgModel){
        [idsDic setObject:@(msgModel.receiveId) forKey:@"主办人"];
        [idsDic setObject:msgModel.superviseId forKey:@"监督人"];
        [idsDic setObject:msgModel.auditId forKey:@"审核人"];
    }
}

-(void)saveContentViewController:(NSNotification *)noti
{
    NSIndexPath *path = [NSIndexPath indexPathForRow:1 inSection:0];
    TSMsgContentItemCell *cell = (TSMsgContentItemCell *)[self cellForRowAtIndexPath:path];
    [cell.contentTextField setText:noti.object];
}

- (void)onMultipleSelectCompelete:(NSNotification *)noti
{
    NSArray *names = [noti.object objectForKey:TSDictionaryKeyDefine_Name];
    NSNumber *type  = (NSNumber *)[noti.object objectForKey:TSDictionaryKeyDefine_Type];
    
    NSIndexPath *path;
    if (type.integerValue == ToolBarTextField_Type_Receive) {
        path = [NSIndexPath indexPathForRow:4 inSection:0];
        [idsDic setObject:[self getIds:names] forKey:@"主办人"];
        
    }
    else if (type.integerValue == ToolBarTextField_Type_Supervise){
        path = [NSIndexPath indexPathForRow:5 inSection:0];
        [idsDic setObject:[self getIds:names] forKey:@"监督人"];
    }
    else if (type.integerValue == ToolBarTextField_Type_Audit){
        path = [NSIndexPath indexPathForRow:6 inSection:0];
        [idsDic setObject:[self getIds:names] forKey:@"审核人"];
    }
    
    TSMsgContentItemCell *cell = (TSMsgContentItemCell *)[self cellForRowAtIndexPath:path];
    
    [cell.contentTextField setText:[self getNames:names]];
    
}

- (NSString *)getIds:(NSArray *)names
{
    NSMutableString *name_str = [[NSMutableString alloc] initWithString:@""];
    if (names && names.count > 0) {
        
        for (int i=0; i<names.count; i++) {
            TSUserModel *model = [names objectAtIndex:i];
            [name_str appendString:model.userId];
            
            if (i < names.count-1) {
                [name_str appendString:@","];
            }
        }
    }
    
    return name_str;
}

- (NSString *)getNames:(NSArray *)names
{
    NSMutableString *name_str = [[NSMutableString alloc] initWithString:@""];
    if (names && names.count > 0) {
        
        for (int i=0; i<names.count; i++) {
            TSUserModel *model = [names objectAtIndex:i];
            [name_str appendString:model.userName];
            
            if (i < names.count-1) {
                [name_str appendString:@","];
            }
        }
    }
    
    return name_str;
}

/* 是否属于picker cell */
- (CELL_TYTPE)getCellType:(NSString *)name
{
    
    if([name isEqualToString:@"类型:"])
        return PICKER_VIEW_TEXT_FIELD_CELL;
    
    NSArray *date_picker_array = @[@"开始时间:",@"结束时间:"];
    
    for (NSString *picker_name in date_picker_array) {
        if ([picker_name isEqualToString:name]) {
            return DATE_PICKER_TEXT_FIELD_CELL;
        }
    }
    
    return DEFAULT_TEXT_FIELD_CELL;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return rowsArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *title = [rowsArray objectAtIndex:indexPath.row];
    if([title isEqualToString:@"内容:"]){
        return 200;
    }else{
        return CELL_HEIGHT;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    NSString *title = [rowsArray objectAtIndex:indexPath.row];
    CELL_TYTPE cell_type = [self getCellType:title];
    
    if (rowsArray && rowsArray.count > indexPath.row) {
        switch (cell_type) {
            case DEFAULT_TEXT_FIELD_CELL:
            {
                NSString *item_cell_identi = [NSString stringWithFormat:@"item_cell_identi%@",@(indexPath.row)];
                TSMsgContentItemCell *item_cell = [tableView dequeueReusableCellWithIdentifier:item_cell_identi];
                if(!item_cell){
                item_cell = [[TSMsgContentItemCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:item_cell_identi];
                }
                [item_cell setTitleAndTextField:title Type:UITextFieldDefault];
                if ([title isEqualToString:@"主办人:"]){
                    [item_cell setToolBarTextFieldType:ToolBarTextField_Type_Receive];
                    [item_cell setNotShowKeyboard:YES];
                    if(msgModel){
                        [item_cell.contentTextField setText:msgModel.receiveName];
                    }
                }
                else if ([title isEqualToString:@"监督人:"]){
                    [item_cell setToolBarTextFieldType:ToolBarTextField_Type_Supervise];
                    [item_cell setNotShowKeyboard:YES];
                    if(msgModel){
                        [item_cell.contentTextField setText:msgModel.receiveName];
                    }
                }
                else if ([title isEqualToString:@"审核人:"]){
                    [item_cell setToolBarTextFieldType:ToolBarTextField_Type_Audit];
                    [item_cell setNotShowKeyboard:YES];
                    if(msgModel){
                        [item_cell.contentTextField setText:msgModel.receiveName];
                    }
                }
                else if ([title isEqualToString:@"内容:"]){
                    [item_cell setToolBarTextFieldType:ToolBarTextField_Type_Content];
                    [item_cell setNotShowKeyboard:YES];
                    if(msgModel){
                        [item_cell.contentTextField setText:msgModel.content];
                    }
                    CGRect frame = item_cell.contentTextField.frame;
                    frame.size.height =180;
                    item_cell.contentTextField.frame = frame;
                }else if([title isEqualToString:@"标题:"]){
                    if(msgModel){
                        [item_cell.contentTextField setText:msgModel.title];
                    }
                }else if([title isEqualToString:@"附件:"]){
                    UIButton * btn = [item_cell replaceRightWithButton:CGSizeMake(100, 60)];
                    [btn setTitle:@"选择附件" forState:UIControlStateNormal];
                    [btn addTarget:self action:@selector(selectFile) forControlEvents:UIControlEventTouchUpInside];
                }
                cell =item_cell;
                item_cell.contentTextField.delegate = self;
            }
                break;
            case DATE_PICKER_TEXT_FIELD_CELL:
            {
                static NSString *picker_cell_identi = @"picker_cell";
                TSMsgDatePickerTextFieldCell *picker_cell = [tableView dequeueReusableCellWithIdentifier:picker_cell_identi];
                if (!picker_cell) {
                    picker_cell = [[TSMsgDatePickerTextFieldCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:picker_cell_identi];
                    [picker_cell setTitle:title];
                    [picker_cell.contentTextField setText:[self getTextByTitle:title]];
                }
                cell = picker_cell;
            }
                break;
            case PICKER_VIEW_TEXT_FIELD_CELL:
            {
                static NSString *picker_cell_identi = @"picker_view_cell";
                TSPickerViewTextFieldCell *picker_view_cell = [tableView dequeueReusableCellWithIdentifier:picker_cell_identi];
                if (!picker_view_cell) {
                    if ([title isEqualToString:@"类型:"]) {
                        picker_view_cell = [[TSPickerViewTextFieldCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:picker_cell_identi WithSourceArray:@[@"不紧急不重要", @"不紧急重要", @"紧急不重要", @"紧急重要"]];
                    }
                    [picker_view_cell setTitle:title];
                    [picker_view_cell.contentTextField setText:[self getTextByTitle:title]];
                }
                cell = picker_view_cell;
            }
                break;
            default:
                break;
        }
    }
    [cellDic setObject:cell forKey:@(indexPath.row)];
    return cell;
}

-(void)selectFile
{
    NSArray *docs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    FBFilesTableViewController * ftView = [[FBFilesTableViewController alloc] initWithPath:docs[0]];
    ftView.vc_root = [self getViewController];
    [self.getViewController.navigationController pushViewController:ftView animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
}

- (UITableViewCell *)getCellByTitle:(NSString *)title
{
    UITableViewCell *cell = [cellDic objectForKey:@([self getIndexPathByTitle:title].row)];
    return cell;
}

- (NSIndexPath *)getIndexPathByTitle:(NSString *)title
{
    if (rowsArray) {
        for (int i=0; i<rowsArray.count; i++) {
            if ([[rowsArray objectAtIndex:i] isEqualToString:title]) {
                NSIndexPath *index_path = [NSIndexPath indexPathForItem:i inSection:0];
                return index_path;
            }
        }
    }
    
    return nil;
}

- (NSString *)getTextByTitle:(NSString *)title
{
    NSString *result_text = @"";
    if (msgModel) {
        if ([title isEqualToString:@"标题:"]) {
            result_text = msgModel.title;
        }
        else if ([title isEqualToString:@"开始时间:"]) {
            result_text = [TSTools getDateByTime:msgModel.timeBegin];
        }
        else if ([title isEqualToString:@"结束时间:"]) {
            result_text = [TSTools getDateByTime:msgModel.timeEnd];
        }
        else if ([title isEqualToString:@"内容:"]) {
            result_text = msgModel.content;
        }
        else if ([title isEqualToString:@"主办人:"]) {
            result_text = msgModel.receiveName;
        }
        else if ([title isEqualToString:@"监督人:"]) {
            result_text = msgModel.receiveName;
        }
        else if ([title isEqualToString:@"审核人:"]) {
            result_text = msgModel.receiveName;
        }else if([title isEqualToString:@"附件:"]){
            //result_text = msgModel.attachment;
        }
    }
    
    return result_text;
}

-(void) keyboardShown:(NSNotification*) notification {
    //isManualScroll= YES;
    // [self setContentOffset:CGPointMake(0.0, 300) animated:YES];
}

-(void) keyboardHidden:(NSNotification*) notification {
    // [self setContentOffset:CGPointMake(0.0, 0) animated:YES];
}
- (void)textViewDidBeginEditing:(UITextView *)textView{
    //    CGFloat y = textView.frame.origin.x;
    //    CGFloat offset = y-currentDeviceHeight+NAV_AND_STATUS_BAR_HEIGHT+316;
    //    if(offset>0){
    //        [self setContentOffset:CGPointMake(0.0, offset) animated:YES];
    //    }
    
    
    UITableViewCell * cell=(UITableViewCell *)[textView  superview];
    NSIndexPath *indexPath=[self indexPathForCell:cell];
    CGFloat heightFormTop = [self getCellHeightFromTop:indexPath.row];
    CGFloat offset = heightFormTop-currentDeviceHeight+NAV_AND_STATUS_BAR_HEIGHT+316;
    if(offset>0){
        [self setContentOffset:CGPointMake(0.0, offset) animated:YES];
    }
    
}
- (void)textViewDidEndEditing:(UITextView *)textView{
    [self setContentOffset:CGPointMake(0.0, 0) animated:YES];
}

-(CGFloat)getCellHeightFromTop:(NSInteger) row
{
    if(row>3){
        return 200+CELL_HEIGHT*row;
    }else{
        return CELL_HEIGHT*(row+1);
    }
}

- (void)saveViewController:(NSNotification *)noti
{
    NSString *editContent = noti.object;
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:3 inSection:0];
    TSMsgContentItemCell *cell = (TSMsgContentItemCell *)[self cellForRowAtIndexPath:indexPath];
    [cell.contentTextField setText:editContent];
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end

